#include "mybattery.h"
#include <QPainter>

MyBattery::MyBattery(QWidget *parent) :
    QWidget(parent)
{
}

int MyBattery::powerLevel() const
{
    return mPowerLevel;
}

void MyBattery::setPowerLevel(int newPowerLevel)
{
    if (mPowerLevel == newPowerLevel)
        return;

    mPowerLevel = newPowerLevel;
    emit powerLevelChanged(mPowerLevel);

    repaint();
}

void MyBattery::setWarnLevel(int warn)
{
    //设置电量低阈值
    mWarnLevel =warn;
    repaint();
}

int MyBattery::warnLevel()
{
    //返回电量低阈值
    return mWarnLevel ;
}


QSize MyBattery::sizeHint()
{
    //缺省大小,调整比例
    int H=this->height();
    int W=H*12/5;

    QSize size(W,H);

    return size;
}

void MyBattery::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    //界面组件绘制
    QPainter painter(this);

    QRect rect(0,0, width(), height());

    painter.setViewport(rect);

    painter.setWindow(rect);

    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    //! 绘制电池边框
    //设置画笔
    QPen pen;
    pen.setWidth(2);
    pen.setColor(mColorBorder);

    pen.setStyle(Qt::SolidLine);
    pen.setCapStyle(Qt::FlatCap);
    pen.setJoinStyle(Qt::BevelJoin);

    painter.setPen(pen);

    //画刷
    QBrush brush;
    brush.setColor(mColorBack);
    brush.setStyle(Qt::SolidPattern);

    painter.setBrush(brush);

    rect.setRect(1,1,109,48);
    //绘制电池边框
    painter.drawRect(rect);
    brush.setColor(mColorBorder);
    painter.setBrush(brush);
    rect.setRect(110,15,10,20);
    //画电池正极头
    painter.drawRect(rect);

    //画电池柱
    if(mPowerLevel > mWarnLevel)
    {
        //正常颜色电量柱
        brush.setColor(mColorPower);
        pen.setColor(mColorPower);
    }
    else
    {
        //电量低电量柱
        brush.setColor(mColorWarning);
        pen.setColor(mColorWarning);
    }

    painter.setBrush(brush);
    painter.setPen(pen);

    if(mPowerLevel > 0)
    {
        //画电池柱
        rect.setRect(5,5,mPowerLevel, 40);
        painter.drawRect(rect);
    }

    //绘制电量百分比文字
    QFontMetrics textsize(this->font());
    QString powStr = QString("%1 %%").arg(mPowerLevel);

    //得到字符串的矩形
    QRect textRect = textsize.boundingRect(powStr);

    painter.setFont(this->font());
    pen.setColor(mColorBorder);
    painter.setPen(pen);

    painter.drawText(55-textRect.width()/2,23+textRect.height()/2,powStr);
}

